package com.hui.demo;

import com.hui.demo.model.Mood;
import com.hui.demo.model.User;
import com.hui.demo.service.MoodService;
import com.hui.demo.service.UserService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest
public class JPATeST {
    @Resource
    private UserService userService;

    @Resource
    private MoodService moodService;

    Logger logger = LogManager.getLogger(this.getClass());

    @Test
    public void testRespository() {
        // 查询所有数据
        List<User> userList = userService.findAll();
        System.out.println("findAll:" + userList.size());

        // 通过name查询数据
        List<User> userList2 = userService.findByUserName("qing");
        System.out.println("findByUserName:" + userList2.size());
        Assert.isTrue(userList2.get(0).getUserName().equals("qing"), "data error");

        // 通过name模糊查询
        List<User> userList3 = userService.findByUserNameLike("%bo%");
        System.out.println("findByUserNameLike:" + userList3.size());
        Assert.isTrue(userList3.get(0).getUserName().equals("bob"), "data error");

        // 通过ID列表查询
        List<String> useerIDs = new ArrayList<>();
        useerIDs.add("1");
        useerIDs.add("2");
        List<User> userrList4 = userService.findByUserIDIn(useerIDs);
        System.out.println("findByUserIDIn:" + userrList4.size());

        // 分页查询
        PageRequest pageRequest = new PageRequest(0,10);
        Page<User> userPage = userService.findAll(pageRequest);
        System.out.println("findAll:" + userPage.getTotalPages() + "/" + userPage.getSize());
        System.out.println(userPage.toString());

        // 新增数据
        User user= new User();
        user.setUserID("3");
        user.setUserName("test2");
        user.setPassword("123456");
        userService.save(user);

        // 删除数据
        userService.delete("3");
    }

    @Test
    public void testTranscation () {
        User user = new User();
        user.setUserID("4");
        user.setUserName("test");
        user.setPassword("123123");
        userService.save(user);
    }

    @Test
    public void testLog4j() {
        userService.delete("4");
        logger.info("delete success");
    }

    @Test
    public void testMood() {
        Mood mood = new Mood();
        mood.setMoodID("1");
        mood.setContent("第一条说说");
        mood.setPraiseNum(1);
        mood.setUserID("1");
        mood.setPublishTime(new Date());
        mood = moodService.save(mood);
    }
}
